package com.duoec.magichour.core.web.freemarker;

import com.google.common.collect.Maps;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * Created by ycoe on 16/5/16.
 */
public class FreemarkerStringFormater {
    private static final Logger logger = LoggerFactory.getLogger(FreemarkerStringFormater.class);

    private static Map<String, Boolean> templateKey = Maps.newConcurrentMap();

    private static Configuration cfg;

    private FreemarkerStringFormater(){}

    public static String format(String templateName, String templateStr, Map<String, Object> vars){
        String templateId = templateName.replaceAll("/", "_");
        StringTemplateLoader templateLoader;
        if(cfg == null) {
            cfg = new Configuration(Configuration.VERSION_2_3_22);
            templateLoader = new StringTemplateLoader();
            cfg.setTemplateLoader(templateLoader);
        }else {
            templateLoader = (StringTemplateLoader) cfg.getTemplateLoader();
        }

        Template template;
        if(!templateKey.containsKey(templateId)) {
            templateLoader.putTemplate(templateId, templateStr);
        }
        try {
            template = cfg.getTemplate(templateId);
            return TemplateModelUtils.renderToString(template, vars);
        } catch (IOException e) {
            logger.error("获取Freemarker模板['" + templateName + "']失败!", e);
        }
        return null;
    }
}
